import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import {
  ICartResult,
  getCart,
  clearCart,
  addShopcart,
  removeShopcartItem,
} from '@/service/shopcart/shopcart'

export const useShopcartStore = defineStore(
  'shopcart',
  () => {
    const shopcartItems = ref<ICartResult[]>([])
    // 初始化购物车
    const initShopcart = async (storeCode: string) => {
      try {
        const response = await getCart(storeCode)
        if (response.success) {
          shopcartItems.value = response.result
        }
      } catch (error) {
        // 处理错误
        // console.error('Failed to initialize shopcart:', error)
      }
    }

    // 添加商品到购物车时，默认为未选中状态
    const addToShopcart = async (item: ICartResult): Promise<boolean> => {
      try {
        const response = await addShopcart({
          price: item.price,
          quantity: item.quantity,
          storeCode: item.storeCode,
          upcCode: item.upcCode,
        })
        // 更新本地状态
        const existingItem = shopcartItems.value.find(
          (shopcartItem) => shopcartItem.upcCode === item.upcCode,
        )
        if (existingItem) {
          existingItem.quantity += item.quantity
        } else {
          shopcartItems.value.push({ ...item })
        }
        if (response.success) {
          uni.showToast({
            title: '加购成功',
            icon: 'none',
          })
        } else {
          uni.showToast({
            title: response.message,
            icon: 'none',
          })
        }
        return response.success
      } catch (error) {
        // 处理错误
        // console.error('Failed to add item to shopcart:', error)
        uni.showToast({
          title: error,
          icon: 'none',
        })
        return false
      }
    }

    // 移除商品
    const removeFromShopcart = async (item: ICartResult) => {
      try {
        const response = await removeShopcartItem({
          price: item.price,
          quantity: item.quantity,
          storeCode: item.storeCode,
          upcCode: item.upcCode,
        })
        if (response.success) {
          // 更新本地状态
          const index = shopcartItems.value.findIndex(
            (shopcartItem) => shopcartItem.upcCode === item.upcCode,
          )
          if (index !== -1) {
            shopcartItems.value.splice(index, 1)
          }
        }
        uni.showToast({
          title: response.message,
          icon: 'none',
        })
      } catch (error) {
        // 处理错误
        // console.error('Failed to remove item from shopcart:', error)
        uni.showToast({
          title: error,
          icon: 'none',
        })
      }
    }

    // 清空购物车
    const clearShopcart = async (storeCode: string) => {
      try {
        const response = await clearCart(storeCode)
        if (response.success) {
          shopcartItems.value = []
        }
        uni.showToast({
          title: response.message,
          icon: 'none',
        })
      } catch (error) {
        // 处理错误
        // console.error('Failed to clear shopcart:', error)
        uni.showToast({
          title: error,
          icon: 'none',
        })
      }
    }

    // 更新商品数量
    const updateQuantity = async (item: ICartResult) => {
      try {
        const response = await addShopcart({
          price: item.price,
          quantity: item.quantity,
          storeCode: item.storeCode,
          upcCode: item.upcCode,
        })
        if (response.success) {
          const existingItem = shopcartItems.value.find(
            (shopcartItem) => shopcartItem.upcCode === item.upcCode,
          )
          if (existingItem) {
            existingItem.quantity = item.quantity
          }
          uni.showToast({
            title: '修改成功',
            icon: 'none',
          })
        }
      } catch (error) {
        // 处理错误
        // console.error('Failed to clear shopcart:', error)
        uni.showToast({
          title: error,
          icon: 'none',
        })
      }
    }

    // 计算选中商品的总价
    const shopcartTotal = computed(() => {
      return shopcartItems.value.reduce((total, item) => {
        const itemTotal = (item.price * item.quantity).toFixed(2) // 四舍五入到两位小数
        return total + Number(itemTotal) // 确保累加的是数字类型
      }, 0)
    })

    const shopcartLength = computed(() => {
      return shopcartItems.value.length
    })

    // 根据ID获取选中商品的数量
    const getSelectedQuantityById = (upcCode: string) => {
      const item = shopcartItems.value.find((shopcartItem) => shopcartItem.upcCode === upcCode)
      return item ? item.quantity : 0
    }

    return {
      shopcartItems,
      addToShopcart,
      removeFromShopcart,
      updateQuantity,
      clearShopcart,
      shopcartTotal,
      getSelectedQuantityById,
      initShopcart,
      shopcartLength,
    }
  },
  {
    persist: true,
  },
)
